/**
 * 
 */
package cc.rico.utils;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ResourceBundle;

import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * es 工具类
 * @author JiWo 2016年7月20日
 *
 */
public class ESUtil {
	private static final Logger logger = LoggerFactory.getLogger(ESUtil.class);
	
//	private static final String ES_CLUSTER_NAME = "elasticsearch";
//	private static final String ES_HOST = "192.168.85.128";
//	private static final int ES_PORT = 9300;
	
	private static Client client;
	
	// 初始化ES
	static {
		try {
			logger.info("#初始化 ESUtil.init...");
			
			// 读取es配置文件信息
			ResourceBundle bundle = ResourceBundle.getBundle("es-config");
			String clusterName = bundle.getString("es.cluster.name");
			String host = bundle.getString("es.host");
			int port = Integer.valueOf(bundle.getString("es.port"));
			logger.info("clusterName={}, host={}, port={}", clusterName, host, port);
			
			Settings settings = Settings.settingsBuilder().put("cluster.name", clusterName).build();
			client = TransportClient.builder()
					.settings(settings)
					.build()
			        .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(host), port));
			
		} catch (UnknownHostException e) {
			logger.error("#初始化发生错误.", e);
		}
	}
	
	/**
	 * 获取es连接
	 * @return
	 */
	public static Client getTransportClient() {
		return client;
	}
	
	/**
	 * 关闭连接
	 * @param client
	 */
	public static void close(Client client) {
		if(client != null) {
			client.close();
		}
	}
	
	public static void main(String[] args) {
		logger.info("try to connect to es client......");
		Client client = ESUtil.getTransportClient();
		
		client.close();
		logger.info("close es client......");
	}
}
